
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ModeloLogicoSistema;

import com.itextpdf.text.BaseColor;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.Font;
import com.itextpdf.text.Rectangle;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

/**
 *
 * @author carlos
 */
public class Imprimir_delivery {

    private File ruta_destino = null;
    private AdministradorOrden adm;
    private AdministradorCliente admC;
    private String fecha_actual = null;
    private String horaDesde = null,
            horaHasta = null,
            monto_total = null,
            descuento = null,
            monto_abonado = null,
            monto_adeudado = null,
            orden = null,
            nombre_cliente = null,
            direccion = null,
            telefono = null,
            nombredelivery = null,
            Precio = null;
    Document mipdf;
    PdfPTable tabla_principal = new PdfPTable(1);
    private FileOutputStream outputStream;

    public Imprimir_delivery(String fecha) throws FileNotFoundException, DocumentException, Exception {

        this.adm = new AdministradorOrden();
        this.admC = new AdministradorCliente();

        ArrayList<Orden> ordenado = this.adm.listadoOrdenadoPorDelivery(fecha);
        if (ordenado.isEmpty()) {
            JOptionPane.showMessageDialog(null, "No hay deliverys en la fecha ingresada");
            return;
        }
        if (!this.Colocar_Destino()) {
            return;
        }

        FileOutputStream outputStream = new FileOutputStream(this.ruta_destino + ".pdf");


        this.tabla_principal.setWidthPercentage(100); //modificamos el ancho de la celda principal


        mipdf = new Document();
        PdfWriter.getInstance(mipdf, outputStream);

        this.tabla_principal.addCell(this.fila1_EncabezadoDelivery());

        for (Orden orden : ordenado) {

            this.horaDesde = orden.getHoraPactadaDesde();
            this.horaHasta = orden.getHoraPactadaHasta();
            this.monto_total = orden.getMontoTotal().toString();
            this.descuento = orden.getDescuento().toString();
            this.monto_abonado = orden.getMontoAbonado().toString();
            this.monto_adeudado = orden.getMontoAdeudado().toString();
            this.orden = orden.getCodOrden().toString();
            Cliente cliente = admC.cargarCliente(orden.getCodCliente());
            this.nombre_cliente = cliente.getNombre() + " " + cliente.getApellido();
            this.direccion = cliente.getCalle() + " " + cliente.getNroCalle() + "  " + cliente.getLocalidad();
            this.telefono = cliente.getTelFijo();

            this.tabla_principal.addCell(this.DisenarTicketUnitario());

        }

        this.CrearTicket();

    }

    private PdfPCell getHorario() {
        PdfPCell cell = new PdfPCell(new Paragraph(" Horario        A partir de las  " + this.horaDesde + "   hasta " + this.horaHasta + "", FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setBorder(Rectangle.NO_BORDER);

        return cell;
    }

    private PdfPCell getMontoTotal() {

        PdfPCell cell = new PdfPCell(new Paragraph(" Monto Total                " + this.monto_total + "", FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setBorder(Rectangle.NO_BORDER);

        return cell;
    }

    private PdfPCell getDescuento() {

        PdfPCell cell = new PdfPCell(new Paragraph(" Descuento             " + this.descuento + "", FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setBorder(Rectangle.NO_BORDER);

        return cell;
    }

    private PdfPCell getMontoAbonado() {

        PdfPCell cell = new PdfPCell(new Paragraph(" Monto Abonado         " + this.monto_abonado + "", FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setBorder(Rectangle.NO_BORDER);

        return cell;
    }

    private PdfPCell getMontoAdeudado() {

        PdfPCell cell = new PdfPCell(new Paragraph(" Monto Adeudado      " + this.monto_adeudado + "", FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setBorder(Rectangle.NO_BORDER);

        return cell;
    }

    private PdfPCell getOrden() {
        PdfPCell cell = new PdfPCell(new Paragraph("Orden: " + this.orden + "", FontFactory.getFont("arial", 10, Font.BOLD, BaseColor.BLACK)));
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setBorder(Rectangle.NO_BORDER);

        return cell;
    }

    private PdfPCell getNombreCliente() {

        PdfPCell cell = new PdfPCell(new Paragraph(" Cliente         " + this.nombre_cliente + "", FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setBorder(Rectangle.NO_BORDER);

        return cell;
    }

    private PdfPCell getDireccion() {

        PdfPCell cell = new PdfPCell(new Paragraph(" Direccion    " + this.direccion + "", FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setBorder(Rectangle.NO_BORDER);

        return cell;
    }

    private PdfPCell getTelefono() {

        PdfPCell cell = new PdfPCell(new Paragraph(" Telefono      " + this.telefono + "", FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setBorder(Rectangle.NO_BORDER);

        return cell;
    }

    public PdfPCell fila1_EncabezadoDelivery() {

        String la_burbuja = "La Burbuja";

        String encabezado = "" + la_burbuja + " ";
        Font fuente1 = new Font(Font.getFamily("ARIAL"), 11, Font.BOLD);
        Paragraph linea = new Paragraph(encabezado, fuente1);                   // creo el encabezado    
        linea.setAlignment(Paragraph.ALIGN_CENTER);
        PdfPCell celda = new PdfPCell();                     // creo la celda 
        celda.setFixedHeight(35);                           // modifica la altura de una celda                

        celda.addElement(linea);

        return celda;
    }

    public PdfPTable fila2_Orden() {

        PdfPTable tabla = new PdfPTable(1);

        tabla.addCell(this.getOrden());

        return tabla;

    }

    private PdfPCell getCell(String text) throws DocumentException, IOException {

        PdfPCell cell = new PdfPCell(new Paragraph("" + text + "", FontFactory.getFont("arial", 8, Font.BOLD, BaseColor.BLACK)));
        cell.setHorizontalAlignment(Element.ALIGN_LEFT);
        cell.setBorder(Rectangle.NO_BORDER);
        return cell;
    }

    public PdfPTable Celda3_DatosCliente() throws DocumentException, IOException {

        PdfPTable tabla = new PdfPTable(2);



        tabla.addCell(this.getNombreCliente());
        tabla.addCell(this.getMontoTotal());
        tabla.addCell(this.getHorario());
        tabla.addCell(this.getMontoAbonado());
        tabla.addCell(this.getTelefono());
        tabla.addCell(this.getMontoAdeudado());
        tabla.addCell(this.getDireccion());
        tabla.addCell(this.getCell("  "));


        if (Double.valueOf(this.descuento) > 0.0) {

            tabla.addCell(this.getDescuento());
        }
        return tabla;
    }

    public PdfPTable DisenarTicketUnitario() throws DocumentException, IOException {
        PdfPTable delivery = new PdfPTable(1);

        // delivery.addCell(this.fila1_EncabezadoDelivery());
        delivery.addCell(this.fila2_Orden());
        delivery.addCell(this.Celda3_DatosCliente());


        return delivery;
    }

    public void CrearTicket() throws DocumentException {

        this.mipdf.open();

        this.mipdf.add(this.tabla_principal);
        mipdf.close();
        byte[] c;
        c = mipdf.toString().getBytes();
        JOptionPane.showMessageDialog(null,
                "Listado de Delivery enviandose a imprimir ....");
        try {
            outputStream = new FileOutputStream(ruta_destino);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        DocFlavor docFormat = DocFlavor.BYTE_ARRAY.AUTOSENSE;
        Doc document = new SimpleDoc(c, docFormat, null);
        PrintRequestAttributeSet attributeSet = new HashPrintRequestAttributeSet(); /// jajaja
        PrintService defaultPrintService = PrintServiceLookup
                .lookupDefaultPrintService();
        System.out.println("Nombre impresora por defecto: "
                + defaultPrintService.getName());
        if (defaultPrintService != null) {

            DocPrintJob printJob = defaultPrintService.createPrintJob();

            try {

                printJob.print(document, attributeSet);

            } catch (Exception e) {

                e.printStackTrace();

            }

        }
    }

    public static String getFechaActual() {
        Date ahora = new Date();
        SimpleDateFormat formateador = new SimpleDateFormat("dd-MM-yyyy");
        return formateador.format(ahora);
    }

    public boolean Colocar_Destino() {
        boolean retorno = false;
        FileNameExtensionFilter filter = new FileNameExtensionFilter(
                "Archivo PDF", "pdf", "PDF");
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setFileFilter(filter);
        fileChooser.setSelectedFile(new File("Delivery " + this.getFechaActual()));
        int result = fileChooser.showSaveDialog(null);

        if (result == JFileChooser.APPROVE_OPTION) {
            this.ruta_destino = fileChooser.getSelectedFile().getAbsoluteFile();
            retorno=true;
        } else {
            JOptionPane.showMessageDialog(null, "No se ha concretado la impresión.");
        }
        return retorno;
    }
}
